package org.example.design.proxy.dynamicproxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author huangshen
 * @version 0
 * @description 动态代理
 * @since 2022/2/6 21:45
 */
@SuppressWarnings("unchecked")
public class ProxyInvocationHandler<E> implements InvocationHandler {

    /**
     * 被代理的接口
     */
    private E target;

    public void setTarget(E target) {
        this.target = target;
    }

    /**
     * 生成代理类
     * @return 代理类
     */
    public E getProxy() {
        return (E)Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces() ,this);
    }

    @Override
    public E invoke(Object proxy, Method method, Object[] args) throws Throwable {
        log(method.getName());
        return (E)method.invoke(target, args);
    }

    private void log(String msg) {
        System.out.println("invoke " + msg + "方法");
    }
}
